from flask import Flask, request, g, jsonify, Response
from .PaddleOCRUtilService import PaddleOCRService
# from .ASRUtilsService import ASRService
from . import config
from . import utils
from . import video_parser
from .ffmpUtils import compress_image
from .asyncUtils import AsyncUtils
from .result import Result

import os

os.environ["KMP_DUPLICATE_LIB_OK"] = "TRUE"

app = Flask(__name__)
# CORS(app, supports_credentials=True)

path = config.config_path
logger = config.logger
# server_executor = ServerExecutor()
user_socket_dict = {}
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024  # 设置上传文件的最大大小为 16MB
app.config['UPLOAD_FOLDER'] = path  # 设置上传文件的保存路径
app.config['ALLOWED_EXTENSIONS'] = {'png', 'jpg', 'jpeg', 'gif'}  # 设置允许上传的文件扩展名

if not os.path.exists(path) and not os.path.isdir(path):
    os.makedirs(path)


# 预解析
# PaddleOCRService()
def get_singleton():
    if not hasattr(g, '_singleton_PaddleOCRService'):
        g._singleton = PaddleOCRService()
    return g._singleton


def files_yield(files):
    for file in files:
        filename = file.filename
        yield filename
        file.save(filename)


def del_file(files):
    try:
        remove = list(map(lambda x: os.remove(x), files))
        AsyncUtils.to_thread(remove)
        del files
        del remove
    except OSError as e:
        print(f"Error deleting file: {e}")


@utils.calc_time
@app.route("/test", methods=["GET"])
def test() -> Response:
    print("测试成功")
    return jsonify(Result.ok(request.args))


@utils.calc_time
@app.route("/parser", methods=["POST"])
def parser() -> dict:
    data = request.args
    filePaths = []
    temps = []
    if data.get("type") == '1':
        url = request.args.get("url")
        suf = url.split(".")[-1]
        file_path = video_parser.async_download_video(url, suf=suf)
        temps.append(file_path)
        filePaths.append(compress_image(file_path))
    elif data.get("type") == '2':
        files = request.files.getlist('file')
        filePaths = list(files_yield(files))
    data = utils.calc_time(AsyncUtils.run)(PaddleOCRService().parserImage_run(filePaths))
    del_file(filePaths + temps)
    return data


@utils.calc_time
@app.route("/parser_url", methods=["GET"])
def parserUrl() -> dict:
    url = request.args.get("url")
    videoPath = video_parser.async_download_video(url)
    # videoPath = path +  "\\test.mp4"
    files = AsyncUtils.run(video_parser.split_video_to_frames(videoPath))
    data = utils.calc_time(AsyncUtils.run)(PaddleOCRService().parserImage_run(files))
    del_file(files)
    return data


# 语音转文字
@utils.calc_time
@app.route("/speechtotext", methods=["POST"])
def speech_to_text():
    data = request.args
    audio_base64, audio_file = None, None
    if data.get("type") == '1':
        audio_base64 = request.get_json().get('audio_base64')  # 要转为文字的语音文件的base64编码，开头含不含'data:audio/wav;base64,'都行
    elif data.get("type") == '2':
        file = request.files['file']
        # 将文件保存到本地
        audio_file = f"{path}/{file.filename}"
        file.save(audio_file)
    elif data.get("type") == '3':
        url = data.get("url")
        audio_file = video_parser.async_download_video(url)
    else:
        return jsonify(Result.error())
    # return jsonify(Result.ok(ASRService().speech_to_text(audio_base64, audio_file)))


# 文字转语音
# 只接受POST方法访问
@utils.calc_time
@app.route("/texttospeech", methods=["POST"])
def text_to_speech():
    text_str = request.get_json().get('text')  # 要转为语音的文字
    # return jsonify(Result.ok(ASRService().text_to_speech(text_str)))


def run():
    app.run(threaded=True, debug=False, host='0.0.0.0', port=5000)
    # http_serve=WSGIServer(("0.0.0.0",5000),app,handler_class=WebSocketHandler)
    # http_serve.serve_forever()
